var editor;
var $userWorkTable=$("#userWorkList")
$(function () {
    // $('#editModels').modal('show');
    $('.filter-content select').val('').selectpicker('refresh');//重置--高级筛选select框

    $('.date-input').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    // 编辑器初始化
    editor = new FroalaEditor('#editor',
        ({
            placeholderText: '',
            charCounterCount: true,//默认 显示字数
            saveInterval: 0,//不自动保存，默认10000，0为不自动保存
            toolbarBottom: false,//默认
            toolbarInline: false,//true选中设置样式,默认false
            imageUploadMethod: 'POST',
            heightMin: 300,
            charCounterMax: 3000,  //最大字数限制，-1为不限制
            // saveURL: '/NewsController/addNotify',  //自动保存的地址（body参数为html内容）
            saveURL: '/knowledgeSection/addKnSection',  //自动保存的地址（body参数为html内容）

            saveParams: {postId: '1'},  //保存内容时传的参数
            spellcheck: false,  //是否允许浏览器对输入内容进行拼写检查
            imageUploadURL: '/file/uploadByOneFileEdit',//上传到本地服务器
            videoUploadURL: '/file/uploadByOneFileEdit',
            imageDefaultWidth: 1300,
            imageResizeWithPercent: true,
            autoHeightEnabled:true,
            language: 'zh_cn',

        }));
    if(location.search==''){
        userWorkList()
    }


    let customerId_data='';


    $(".customerId").on('shown.bs.select',function(e) {

        if(customerId_data==''){

            let send_data='<option value="">加载中。。。</option>'
            $("#customerIdMS").html(send_data);
            $('.customerId').selectpicker('refresh');
            setTimeout(function () {
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: '/customerController/getCustomerList',
                    cache : false,
                    data:{
                    },
                    async : false,
                    success: (function (data) {
                        if (data.code == "000000") {
                            //<option value="">请选择</option>
                            var html = '';
                            $.each(data.data, function(n, value) {
                                //selected
                                if(value.customerId==$(".cust-select").val()){
                                    html += "<option value=" + value.customerId + " selected>" +  value.customerName + "</option>";
                                }else{
                                    html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";
                                }


                            });
                            customerId_data=html
                            $("#customerIdMS").html(html);
                            // $('.customerId').selectpicker('refresh')

                            $("#customerIdMS").html(html).selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                                if($('.form-horizontal').data('bootstrapValidator')!=undefined){
                                    $('.form-horizontal').data('bootstrapValidator')
                                        .updateStatus('customerIdMS', 'NOT_VALIDATED',null)
                                        .validateField('customerIdMS');
                                }
                            });



                        } else {
                            alert("请求失败");
                        }
                    }),
                    error: (function (res) {
                        alert("请求失败");
                    }),

                });
            },100)

        }
        else{
            $("#customerIdMS").html(customerId_data);
            // $('.customerId').selectpicker('refresh')

            $("#customerIdMS").html(customerId_data).selectpicker('refresh').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {      // 内容变更触发
                if($('.form-horizontal').data('bootstrapValidator')!=undefined){
                    $('.form-horizontal').data('bootstrapValidator')
                        .updateStatus('customerIdMS', 'NOT_VALIDATED',null)
                        .validateField('customerIdMS');
                }
            });
        }


    })
    $('#editModels').on('hidden.bs.modal', function () {
        customerId_data=''
    })
})
function addContact() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增日志',
        url: "/front/workLog/addWorkLog?bs=1"
    }, true);
}

function workLog() {
    userWorkList()
}
/**
*
* table
* */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.bs = 1;//标识
    //搜索条件
    params.userName=$.trim($('#userName').val());//所有人
    params.dateType=$.trim($('#dateType').val());//全部、本月

    params.startTm=$.trim($('#startTm').val()); //开始时间
    params.endTm=$.trim($('#endTm').val()); //结束时间
    params.logType=$.trim($('#logType').val()); //日志类型

    params.logName=$.trim($('#logName').val()); //日志类型



    if(location.search){
        params.customerId=$.trim($('#customerId').text()); //
    }

    return params;
}
function userWorkList() {
//先销毁表格
    $userWorkTable.bootstrapTable('destroy');
    $userWorkTable.bootstrapTable({
        classes: 'table table-hover table-bordered',
        url: '/workLog/selectWorkLogListByPage',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'logId',
        idField: 'logId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[10]",//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'logId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '60', formatter: indexFormat},
            {title: '日志标题', field: 'logName', align: 'left', valign: 'middle'},
            {title: '类型', field: 'logType', align: 'left', valign: 'middle', formatter: matterType},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle', sortable: true},
            // {title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', events: editInfo,
                formatter: function genderOpt(value, row, index) {
                    let html = '';
                    // html += '<button type="button" class="btn btn-default" id="seeContent">查看</button>';
                    html += '<button class="js-create-tab btn btn-default" data-title="日志详情" data-url="front/workLog/viewWorkLog?logId=' + row.logId + '"> 查看</button>';
                    html += '<button type="button" class="btn btn-default" id="deletTd">删除</button>';
                    html += '<button type="button" class="btn btn-default" id="editInfo">修改</button>';

                    // let today = new Date().Format('yyyy-MM-dd')
                    // var v=$.trim($('#isAdmin').val());
                    // if (v == "" && $("#qx").val() == 2){//只限制用户
                    //     if(row.planDate == today){//判断是否是当天的计划
                    //         html += '<button type="button" class="btn btn-default" onclick="delFollowPlan(\'' + row.cpFollowPlanId + '\',1)">取消</button>';
                    //     }
                    // }else{
                    //     html += '<button type="button" class="btn btn-default" onclick="delFollowPlan(\'' + row.cpFollowPlanId + '\',2)">取消</button>';
                    // }
                    // html += '</ul></div>'
                    return html;
                }
            }
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
            //
            // // table列可拖动宽度
            // $('.JCLRgrips').remove();
            // $('#orderTableList').css({
            //     minWidth: $('#orderTableList').width()
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0, 11,],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            //     /*onResize: function () {
            //     }*/
            // });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
function indexFormat(value, row, index) {
    return index + 1;
}

function matterType(value, row, index) {
    let html='';
    switch (value) {
        case 0:
            html = "无";
            break;
        case 1:
            html = "客户落实";
            break;
        case 2:
            html = "日常沟通";
            break;
        case 3:
            html = "需求挖掘";
            break;
        case 4:
            html = "会员维护";
            break;
        case 5:
            html = "促单";
            break;
    }
    return html;
}
/**
* table的查看，删除和修改
* */
var editInfo = {
    'click #seeContent': function(e, value, row, index) {
        // 查看

        $(".modal-header h4").html('查看')
        $(".edit-submit").hide()
        $("#logId").val(row.logId)
        $("#workOrderTitle").val(row.logName)
        $("#workOrderType").val(row.logType)
        $("#editor .fr-view").html(row.logContent)


        let val_data="<option value=" + row.customerId + ">" +  row.customerName + "</option>";
        $(".customerId").html(val_data);
        $('.customerId').selectpicker('refresh');


        $('#editModels').modal('show');

    },
    'click #deletTd': function(e, value, row, index) {
        // 删除
        let logId=row.logId



        $.confirm({
            title: '提示',
            content: '您确认要删除吗？',
            buttons: {
                ok: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function() {
                        $.ajax({
                            url: '/workLog/delLogById/'+logId,
                            type: 'POST',
                            dataType:"json",
                            success:function (result) {
                                if(result.code=='000000'){
                                    // $('#editModels').modal('hide');
                                    $.alert('删除成功')
                                    $userWorkTable.bootstrapTable('refresh')
                                }else{
                                    $.alert('删除失败')
                                }
                            },
                            error:function (res) {
                                $.alert('删除失败')
                            }
                        })
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'btn-default'
                }
            }
        })







    },
    'click #editInfo': function(e, value, row, index) {
        $(".modal-header h4").html('修改')
        $(".edit-submit").show()
        $("#logId").val(row.logId)
        $("#workOrderTitle").val(row.logName)
        $("#workOrderType").val(row.logType)
        $('#workOrderType').selectpicker('refresh');
        $("#editor .fr-view").html(row.logContent)

        let val_data="<option value=" + row.customerId + ">" +  row.customerName + "</option>";

        $(".cust-select").val(row.customerId)
        $("#customerIdMS").html(val_data);
        $('.customerId').selectpicker('refresh');

        $('#editModels').modal('show');



    }
}

//修改提交
function editSubmit() {
    $('.form-horizontal').bootstrapValidator({
        fields: {
            workOrderTitle: {
                validators: {
                    notEmpty: {
                        message: '标题不能为空'
                    },
                    regexp: {
                        regexp: /^[\u4e00-\u9fa5A-Za-z0-9_-]+[\)）（，；\(\.\%。\u4e00-\u9fa5A-Za-z0-9_-]?$/,
                        message: '请输入正确的标题'
                    }
                }
            },
            workOrderType: {
                validators: {
                    notEmpty: {
                        message: '类型不能为空'
                    }
                }
            },
            customerIdMS: {
                validators: {
                    notEmpty: {
                        message: '客户名称不能为空'
                    }
                }
            },

        },
    })
    $(".form-horizontal").bootstrapValidator('validate');//提交验证
    if (!$(".form-horizontal").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码

        return;
    }
    let obj={
        logId:$("#logId").val(),
        logName:$("#workOrderTitle").val(),
        logType:$("#workOrderType").val(),
        logContent:$("#editor .fr-view").html(),
        customerId:$("#customerIdMS").val()
    }
    // 修改标题
    $.ajax({
        url: '/workLog/updateWorkLog',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify(obj),
        async: false,
        success: (function (data) {
            if(data.code=='000000'){
                $.alert({
                    title: '提示',
                    content: '修改成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                //模态框关闭
                                $('#editModels').modal('hide');
                                $userWorkTable.bootstrapTable('refresh')
                            }
                        }
                    }
                })
            }else{
                $.alert('修改失败')
            }
        }),
        error: (function (res) {
            $.alert('修改失败')
        })

    })
}

//搜索所有人

function searchUserName() {
    $userWorkTable.bootstrapTable('refreshOptions', { queryParams: queryParams});
}

//日期 全部、上月
function selectTime(obj,i) {
    $('.filter-content input').val('');
    $('.filter-content select').val('').selectpicker('refresh');//重置--高级筛选select框
    $('#filterContent').collapse('hide')



    $("#dateType").val(i)
    $(obj).addClass('active-second');
    $(obj).siblings().removeClass('active-second');
    // $(this).addClass('active-second');
    $userWorkTable.bootstrapTable('refreshOptions', { queryParams: queryParams});
}

// 高级筛选
function seniorSearch() {

    $userWorkTable.bootstrapTable('refreshOptions', { queryParams: queryParams});
}

//重置
$("#btn-reset").on('click',function () {
    $('.filter-content input').val('');
    $('.filter-content select').val('').selectpicker('refresh');//重置--高级筛选select框
    $userWorkTable.bootstrapTable('refreshOptions', { queryParams: queryParams});
})



